package com.sunwayworld.basemodule.business.utils;

import com.sunwayworld.framework.exception.FtpException;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.commons.net.ftp.FTPSClient;
import java.nio.charset.StandardCharsets;

/*
 * 安全加密ftps工具类
 * */
public class FtpsUtils {

    public static FTPSClient getFtpsClient(String ip, int port, String user, String password) {
        FTPSClient ftpsClient = new FTPSClient("SSL");
        try {
            ftpsClient.connect(ip, port);
            ftpsClient.enterLocalPassiveMode();
            boolean loginSuccess = ftpsClient.login(user, password);
            if (!loginSuccess) {
                throw new FtpException("FTPS 登录失败");
            } else {
                ftpsClient.setFileTransferMode(FTP.STREAM_TRANSFER_MODE);
                ftpsClient.setFileType(FTPClient.BINARY_FILE_TYPE);
                ftpsClient.execPBSZ(0);
                ftpsClient.execPROT("P");
                if (FTPReply.isPositiveCompletion(ftpsClient.sendCommand("OPTS UTF8", "ON"))) {
                    ftpsClient.setControlEncoding(StandardCharsets.UTF_8.name());
                } else {
                    ftpsClient.setControlEncoding("GBK");
                }
                return ftpsClient;
            }
        } catch (Exception e) {
            throw new FtpException("FTPS 连接异常", e);
        }
    }

}
